/// Copyright (c) Microsoft Corporation.  All rights reserved.
/// 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Microsoft.VSPowerToys.PackInstaller
{
	public partial class MultipleLicenseAgreementForm : Form
	{
		int checkPrint;

		/// <summary>
		/// Constructor, sets the default fonts we want on a couple elements.
		/// </summary>
		public MultipleLicenseAgreementForm()
		{
			InitializeComponent();

			this.Font = SystemFonts.DialogFont;
			this.licenseAgreementTextBox.Font = SystemFonts.CaptionFont;
		}

		/// <summary>
		/// This method initializes the data elements on the form with the data passed in
		/// by the caller.
		/// When you reassign the toolsLicenseData object the toolLicensesGrid data references
		/// need to be updated, otherwise they don't work.
		/// </summary>
		/// <param name="licenseAgreementData"></param>
		public void SetLicenseAgreementData(ToolsLicenseList licenseAgreementData)
		{
			if (licenseAgreementData != null)
			{
				toolsLicenseData = licenseAgreementData;
				toolLicensesGrid.DataSource = toolsLicenseData;
				toolLicensesGrid.DataMember = "LicenseEntry";
			}
		}

		/// <summary>
		/// This event is raised when the form is first shown.  We want to make sure that the grid starts out with
		/// no elements selected, and the text box that holds the license agreements has focus.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MultipleLicenseAgreementForm_Shown(object sender, EventArgs e)
		{
			this.toolLicensesGrid.Rows[0].Selected = false;
		}

		/// <summary>
		/// This event is raised when the "content" portion of a grid cell is clicked.
		/// We want to use this event to handle the links to the license agreements getting clicked.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void toolLicensesGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex == toolLicensesGrid.Columns["licenseNameDataGridViewTextBoxColumn"].Index)
			{
				if (e.RowIndex >= 0)
				{
                    ViewLicense(e.RowIndex);
				}
			}
		}

		/// <summary>
		/// This event is raised when the user clicks the Print license... button.
		/// We want to show the print dialog
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void printLicenseButton_Click(object sender, EventArgs e)
		{
			printDialog1.Document = licenseDocument;
			if (printDialog1.ShowDialog() == DialogResult.OK)
			{
				licenseDocument.Print();
			}
		}

		/// <summary>
		/// The PrintPage event is sent each time a page needs to be printed.
		/// This code is lifted mostly from the MSDN article about using the PrintDocument object.
		/// <param name="sender"
		/// <param name="e"></param>
		/// </summary>
		private void licenseDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
		{
			// Print the content of RichTextBox. Store the last character printed.
			checkPrint = licenseAgreementTextBox.Print(checkPrint, licenseAgreementTextBox.TextLength, e);

			// Check for more pages
			if (checkPrint < licenseAgreementTextBox.TextLength)
				e.HasMorePages = true;
			else
				e.HasMorePages = false;
		}

		/// <summary>
		/// The BeginPrint event is sent when printing begins for the document.
		/// This code resets the counter used by the PrintPage event to print the RichTextBox
		/// <param name="sender"
		/// <param name="e"></param>
		/// </summary>
		private void licenseDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
		{
			checkPrint = 0;
		}

        /// <summary>
        /// We need to make sure the decline button is the default, the best place to do this
        /// is in the load event before the form appears on the screen.  To do that here we have to use the Select method
        /// as focus can't be set yet.
        /// We also need to load the text for the bottom panel from the rich text stream so we can have nice text formatting.
        /// </summary>
        /// <param name="sender"
        /// <param name="e"></param>
        private void MultipleLicenseAgreementForm_Load(object sender, EventArgs e)
        {
            this.declineButton.Select();
            this.licenseReminderTextBox.Rtf = Strings.LicenseAgreementReminderRichText;
        }

        /// <summary>
        /// This event is raised when the user lets go of a keyboard key.  We want to trap the spacebar on the first column
        /// to make it act like the link column
        /// </summary>
        /// <param name="sender"/>
        /// <param name="e"/>
        private void toolLicensesGrid_KeyUp(object sender, KeyEventArgs e)
        {
            if (toolLicensesGrid.CurrentCell.ColumnIndex == toolLicensesGrid.Columns["toolNameDataGridViewTextBoxColumn"].Index)
            {
                if (e.KeyCode == Keys.Space)
                {
                    if (toolLicensesGrid.CurrentCell != null)
                    {
                        ViewLicense(toolLicensesGrid.CurrentCell.RowIndex);
                    }
                }
            }
        }

        /// <summary>
        /// This method puts up a license in the viewer area.  Licenses are referenced by index.
        /// </summary>
        /// <param name="whichLicense"/>
        private void ViewLicense(int whichLicense)
        {
            if (File.Exists(toolsLicenseData.LicenseEntry[whichLicense].LicenseFileName))
            {
                currentlyViewingLabel.Text = Strings.CurrentlyViewingLicensePrefix + toolsLicenseData.LicenseEntry[whichLicense].ToolName + Strings.CurrentlyViewingLicensePostfix;
                this.licenseAgreementTextBox.Font = null;
                this.printLicenseButton.Enabled = true;

                try
                {
                    licenseAgreementTextBox.LoadFile(toolsLicenseData.LicenseEntry[whichLicense].LicenseFileName);
                }
                catch (ArgumentException)
                {
                    try
                    {
                        licenseAgreementTextBox.LoadFile(toolsLicenseData.LicenseEntry[whichLicense].LicenseFileName, RichTextBoxStreamType.PlainText);
                    }
                    catch (ArgumentException)
                    {
                        // Eat this exception...
                    }
                    catch (IOException)
                    {
                        // Eat this exception...
                    }
                }
            }

        }
	}
}